package com.example.aevovein;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;

import com.example.aevovein.databinding.ActivityMainBinding;
import com.example.aevovein.ui.skilltree.SkilltreeFragment;
import com.example.aevovein.data.DataInitializer;
import java.io.File;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_MANAGE_STORAGE = 1;
    private ActivityMainBinding binding;
    private boolean hasStoragePermission = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 检查存储权限
        checkStoragePermission();
    }

    private void checkStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                showPermissionDialog();
            } else {
                hasStoragePermission = true;
                initializeApp();
            }
        } else {
            hasStoragePermission = true;
            initializeApp();
        }
    }

    private void showPermissionDialog() {
        new AlertDialog.Builder(this)
            .setTitle("需要存储权限")
            .setMessage("应用需要管理所有文件的权限来保存技能数据。请授予权限以继续使用。")
            .setPositiveButton("去设置", (dialog, which) -> {
                try {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                    intent.addCategory("android.intent.category.DEFAULT");
                    intent.setData(Uri.parse(String.format("package:%s", getApplicationContext().getPackageName())));
                    startActivityForResult(intent, REQUEST_MANAGE_STORAGE);
                } catch (Exception e) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                    startActivityForResult(intent, REQUEST_MANAGE_STORAGE);
                }
            })
            .setNegativeButton("退出", (dialog, which) -> finish())
            .setCancelable(false)
            .show();
    }

    private void initializeApp() {
        // 创建数据目录和文件
        File dataDir = new File(Environment.getExternalStorageDirectory(), "AevoVein/data");
        if (!dataDir.exists()) {
            if (!dataDir.mkdirs()) {
                Toast.makeText(this, "创建数据目录失败", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 添加技能树Fragment
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, new SkilltreeFragment());
        transaction.commit();

        // 初始化数据
        checkAndInitData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_MANAGE_STORAGE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    hasStoragePermission = true;
                    initializeApp();
                } else {
                    showPermissionDialog();
                }
            }
        }
    }

    private void checkAndInitData() {
        try {
            DataInitializer dataInitializer = new DataInitializer(this);
            dataInitializer.initializeData();
        } catch (Exception e) {
            Toast.makeText(this, "数据初始化失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }
}